package com.example.project.service.base.impl;

import com.example.project.exception.RequestException;
import com.example.project.model.config.BaseErrorConfigEnum;
import com.example.project.service.base.BaseBusinessService;
import org.modelmapper.ModelMapper;
import org.modelmapper.convention.MatchingStrategies;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.Type;
import java.util.List;
import java.util.Optional;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: deep
 * \* Date: 17-9-10
 * \* Time: 下午1:50
 * \* To change this template use File | Settings | File Templates.
 * \* Description:
 * \
 */
public class BaseBusinessServiceImpl<T> implements BaseBusinessService<T> {

    private   Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    ModelMapper modelMapper;

    public ModelMapper getModelMapper() {
        modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
        return modelMapper;
    }

    public void setModelMapper(ModelMapper modelMapper) {
        this.modelMapper = modelMapper;
    }

    public Logger getLogger() {
        return logger;
    }

    public void setLogger(Logger logger) {
        this.logger = logger;
    }

    /**
     * 转换entity到dto对象
     * @param source
     * @param destinationType 示例 :UserResponse.class
     * @param <D>
     * @return
     */
    public <D> D converterObject(Object source, Class<D> destinationType) {
        try {
            if(Optional.ofNullable(source).isPresent()){
                return  this.getModelMapper().map(source,destinationType);
            }
            return null;
        }catch (Exception e){
            logger.error(BaseErrorConfigEnum.CONVERTER_FAIL.getValue());
            throw new RequestException(BaseErrorConfigEnum.CONVERTER_FAIL);
        }
    }


    /**
     * 转换entity到dto对象(集合)
     * @param source
     * @param type 示例 :new TypeToken<List<UserOauthResponse>>(){}.getType()
     * @param <D>
     * @return
     */
    public <D> D converterList(Object source, Type type) {
        try {
            if(Optional.ofNullable(source).isPresent()){
                if(source instanceof List){
                    List o=(List)source;
                    if(Optional.ofNullable(o).filter(list->list.size()>0).isPresent()){
                        return  this.getModelMapper().map(source,type);
                    }
                }
            }
            return null;
        }catch (Exception e){
            logger.error(BaseErrorConfigEnum.CONVERTER_FAIL.getValue());
            throw new RequestException(BaseErrorConfigEnum.CONVERTER_FAIL);
        }
    }

}
